<template>
  <div class="admin-exam-outlines">
    <div class="page-header">
      <h1>考纲管理</h1>
      <p>管理校测考纲和相关文档</p>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="院校">
          <el-select v-model="searchForm.schoolId" placeholder="选择院校" clearable>
            <el-option v-for="school in schools" :key="school.id" :label="school.name" :value="school.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="专业">
          <el-select v-model="searchForm.majorId" placeholder="选择专业" clearable>
            <el-option v-for="major in majors" :key="major.id" :label="major.name" :value="major.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="年份">
          <el-date-picker
            v-model="searchForm.examYear"
            type="year"
            placeholder="选择年份"
            value-format="YYYY"
          />
        </el-form-item>
        <el-form-item label="考试类型">
          <el-select v-model="searchForm.examType" placeholder="考试类型" clearable>
            <el-option label="校测" value="school_test" />
            <el-option label="面试" value="interview" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadOutlines">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>考纲列表</span>
          <div>
            <el-button type="primary" @click="addOutline">添加考纲</el-button>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="outlines" stripe>
        <el-table-column prop="title" label="考纲标题" />
        <el-table-column prop="examYear" label="年份" width="80" />
        <el-table-column prop="examType" label="考试类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.examType === 'school_test' ? 'primary' : 'success'">
              {{ row.examType === 'school_test' ? '校测' : '面试' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="subjectName" label="科目" />
        <el-table-column prop="totalScore" label="总分" width="80" />
        <el-table-column prop="examDuration" label="时长(分)" width="100" />
        <el-table-column prop="downloadCount" label="下载量" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 2 ? 'success' : 'warning'">
              {{ row.status === 2 ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="viewOutline(row)">查看</el-button>
            <el-button size="small" type="primary" @click="editOutline(row)">编辑</el-button>
            <el-button 
              v-if="row.status !== 2" 
              size="small" 
              type="success" 
              @click="publishOutline(row)"
            >
              发布
            </el-button>
            <el-button size="small" type="danger" @click="deleteOutline(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadOutlines"
          @current-change="loadOutlines"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="formDialogVisible" 
      :title="formMode === 'add' ? '添加考纲' : '编辑考纲'" 
      width="800px"
    >
      <el-form :model="outlineForm" :rules="formRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="院校" prop="schoolId">
              <el-select v-model="outlineForm.schoolId" placeholder="选择院校">
                <el-option v-for="school in schools" :key="school.id" :label="school.name" :value="school.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业">
              <el-select v-model="outlineForm.majorId" placeholder="选择专业（可选）">
                <el-option v-for="major in formMajors" :key="major.id" :label="major.name" :value="major.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="考纲标题" prop="title">
              <el-input v-model="outlineForm.title" placeholder="请输入考纲标题" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="年份" prop="examYear">
              <el-date-picker
                v-model="outlineForm.examYear"
                type="year"
                placeholder="选择年份"
                value-format="YYYY"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="考试类型" prop="examType">
              <el-select v-model="outlineForm.examType">
                <el-option label="校测" value="school_test" />
                <el-option label="面试" value="interview" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="科目名称">
              <el-input v-model="outlineForm.subjectName" placeholder="科目名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="考试时长">
              <el-input-number v-model="outlineForm.examDuration" :min="0" placeholder="分钟" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总分">
              <el-input-number v-model="outlineForm.totalScore" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="考试形式">
              <el-select v-model="outlineForm.examFormat">
                <el-option label="笔试" value="written" />
                <el-option label="口试" value="oral" />
                <el-option label="实践" value="practical" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="考纲内容">
          <el-input v-model="outlineForm.outlineContent" type="textarea" :rows="6" />
        </el-form-item>
        
        <el-form-item label="知识点">
          <el-input v-model="outlineForm.knowledgePoints" type="textarea" :rows="4" />
        </el-form-item>
        
        <el-form-item label="参考书目">
          <el-input v-model="outlineForm.referenceBooks" type="textarea" :rows="3" />
        </el-form-item>
        
        <el-form-item label="考纲文件">
          <el-input v-model="outlineForm.fileUrl" placeholder="文件URL（可选）" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="formDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'

// 响应式数据
const loading = ref(false)
const outlines = ref([])
const schools = ref([])
const majors = ref([])
const formMajors = ref([])

const searchForm = reactive({
  schoolId: '',
  majorId: '',
  examYear: '',
  examType: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const formDialogVisible = ref(false)
const formMode = ref('add')
const outlineForm = reactive({
  id: null,
  schoolId: '',
  majorId: '',
  title: '',
  examYear: new Date().getFullYear().toString(),
  examType: 'school_test',
  subjectName: '',
  examDuration: 120,
  totalScore: 100,
  examFormat: 'written',
  outlineContent: '',
  knowledgePoints: '',
  referenceBooks: '',
  fileUrl: ''
})

const formRules = {
  schoolId: [{ required: true, message: '请选择院校', trigger: 'change' }],
  title: [{ required: true, message: '请输入考纲标题', trigger: 'blur' }],
  examYear: [{ required: true, message: '请选择年份', trigger: 'change' }],
  examType: [{ required: true, message: '请选择考试类型', trigger: 'change' }]
}

// 方法
const loadOutlines = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    const { data } = await api.get('/exam/outlines/admin', { params })
    outlines.value = data.records || []
    pagination.total = data.total || 0
  } catch (error) {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const loadSchools = async () => {
  try {
    const { data } = await api.get('/schools')
    schools.value = data.records || []
  } catch (error) {
    console.error('加载院校失败:', error)
  }
}

const loadMajors = async () => {
  if (searchForm.schoolId) {
    try {
      const { data } = await api.get('/majors', { 
        params: { schoolId: searchForm.schoolId } 
      })
      majors.value = data.records || []
    } catch (error) {
      console.error('加载专业失败:', error)
    }
  } else {
    majors.value = []
  }
}

const loadFormMajors = async () => {
  if (outlineForm.schoolId) {
    try {
      const { data } = await api.get('/majors', { 
        params: { schoolId: outlineForm.schoolId } 
      })
      formMajors.value = data.records || []
    } catch (error) {
      console.error('加载专业失败:', error)
    }
  } else {
    formMajors.value = []
  }
}

const resetSearch = () => {
  Object.assign(searchForm, {
    schoolId: '',
    majorId: '',
    examYear: '',
    examType: ''
  })
  majors.value = []
  loadOutlines()
}

const addOutline = () => {
  formMode.value = 'add'
  Object.assign(outlineForm, {
    id: null,
    schoolId: '',
    majorId: '',
    title: '',
    examYear: new Date().getFullYear().toString(),
    examType: 'school_test',
    subjectName: '',
    examDuration: 120,
    totalScore: 100,
    examFormat: 'written',
    outlineContent: '',
    knowledgePoints: '',
    referenceBooks: '',
    fileUrl: ''
  })
  formDialogVisible.value = true
}

const editOutline = (row) => {
  formMode.value = 'edit'
  Object.assign(outlineForm, { ...row })
  formDialogVisible.value = true
  loadFormMajors()
}

const submitForm = async () => {
  try {
    if (formMode.value === 'add') {
      await api.post('/exam/outlines', outlineForm)
      ElMessage.success('添加成功')
    } else {
      await api.put(`/exam/outlines/${outlineForm.id}`, outlineForm)
      ElMessage.success('更新成功')
    }
    formDialogVisible.value = false
    loadOutlines()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const viewOutline = (row) => {
  ElMessage.info('查看详情功能待实现')
}

const publishOutline = async (row) => {
  try {
    await ElMessageBox.confirm('确认发布此考纲？', '确认发布')
    await api.put(`/exam/outlines/${row.id}/publish`)
    ElMessage.success('发布成功')
    loadOutlines()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发布失败')
    }
  }
}

const deleteOutline = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除此考纲？', '确认删除', { type: 'warning' })
    await api.delete(`/exam/outlines/${row.id}`)
    ElMessage.success('删除成功')
    loadOutlines()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 监听
watch(() => searchForm.schoolId, () => {
  searchForm.majorId = ''
  loadMajors()
})

watch(() => outlineForm.schoolId, () => {
  outlineForm.majorId = ''
  loadFormMajors()
})

// 初始化
onMounted(() => {
  loadOutlines()
  loadSchools()
})
</script>

<style lang="scss" scoped>
.admin-exam-outlines {
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      margin: 0 0 8px 0;
      font-size: 24px;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #909399;
    }
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
}
</style>